package kr.hkit.password.fragment.dialog;

import kr.hkit.password.R;
import kr.hkit.password.dao.InfoDao;
import kr.hkit.password.db.MyDatabaseManager;
import kr.hkit.password.service.AlarmService;
import android.app.ActionBar.LayoutParams;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Switch;

public class DialogAlarm extends DialogFragment {
	private static final String TAG = "PW";
	private Button btnSet;
	private Switch sAlarm;
	private InfoDao info;
	private MyDatabaseManager mAdb;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.d(TAG, "DialogSetting onCreateView");
		View view = inflater.inflate(R.layout.dialog_alarm, container, false);
		
		info = (InfoDao) getActivity().getApplication();
		info.setMain(false);
		mAdb = MyDatabaseManager.getInstance(getActivity());
		
		sAlarm = (Switch) view.findViewById(R.id.alarmSwitch);
		sAlarm.setChecked(info.isAlarmUse());
		btnSet = (Button) view.findViewById(R.id.btnSet);
		btnSet.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.d(TAG, "AccountSetting onClick");
				ContentValues addRowValue = new ContentValues();
				addRowValue.put("alarm", sAlarm.isChecked()?1:0 );
				mAdb.update("account", addRowValue, "account=?", new String[] {info.getAccount()});
				Intent intent;
				if (sAlarm.isChecked()){
					intent = new Intent(getActivity(), AlarmService.class);
					getActivity().startService(intent);
				} else {
					intent = new Intent(getActivity(), AlarmService.class);
					getActivity().stopService(intent);
				}
				info.setAlarmUse(sAlarm.isChecked());
				Log.d(TAG, "AccountSetting alarm = " + (sAlarm.isChecked()?1:0));
				dismiss();
			}
		});
		
		return view;
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		Dialog dialog = new Dialog(getActivity());
		dialog.setContentView(R.layout.dialog_alarm);
		dialog.setTitle("알람 설정");
		WindowManager.LayoutParams param = dialog.getWindow().getAttributes();
		param.width = 200;
		param.height = 200;
		return dialog;
	}
}
